<template>
  <div class="auth-product partDetailsBox">
    <el-container class="partDetails">
      <!-- 列表 -->
      <el-header style="height: auto;">
        <RecordInfo
          :record-form="recordFormDetail"
          :record-data="headerInfo">
          <template v-slot:recordInfoslot="slotProp">
            <div class="solt-info">
              <span class="left-span">
                医院采购产品总数
                <span class="right-span">{{ headerInfo.prodTotalCount }}</span>
              </span>
              <span>
                品种数
                <span>{{ headerInfo.prodTypeCount }}</span>
              </span>
              <span>
                金额合计 （元）:
                <span>
                  <span class="price">{{ headerInfo.orderAmount | getFormatterPrice }}</span>
                </span>
              </span>
            </div>
          </template>
        </RecordInfo>
      </el-header>
      <SearchForm
        :data="detailsSearchFormFailed"
        @searchForm="searchForm"
        @resetForm="resetForm"
        :submit-loading='submitLoading'
      />
      <el-editable
        class="hospital-edit-box"
        :data="pssCompareHspList"
        :row-style="getRowStyle"
        height="600"
        v-loading="tableLoading"
        :span-method="pssSpanMethod"
        :columns="partFailtedDetailsTableData"
      >
        <template
          slot="default-index"
          slot-scope="scope">
          <span v-if="!(scope.$index % 2)">{{ scope.$index / 2 + 1 }}</span>
        </template>
        <template
          slot="default-pssProdCode"
          slot-scope="scope">
          <div>
            <span v-if="scope.$index % 2">{{ scope.row.pssProdCode }}</span>
            <el-select
              v-else
              v-model="scope.row.pssProdCode"
              filterable
              clearable
              @input.native="getValue"
              :filter-method="getProdListByCompanyProdCode"
              @change="setProdInfoByCompanyProdCode($event, scope.row)"
              @focus="getProdListByCompanyProdCode(scope.row.pssProdCode)"
              placeholder="请选择">
              <el-option
                v-for="item in prodOptions"
                :key="item.id"
                :title="item.companyProdCode"
                :label="item.companyProdCode"
                :value="item.companyProdCode"/>
            </el-select>
          </div>
        </template>
        <template
          slot="default-pssProdName"
          slot-scope="scope">
          <div>
            <span v-if="scope.$index % 2">{{ scope.row.pssProdName }}</span>
            <el-select
              v-else
              v-model="scope.row.pssProdName"
              filterable
              clearable
              :filter-method="getProdListByProdNameCn"
              @input.native="getValue"
              @change="setProdInfoByProdNameCn($event, scope.row)"
              @focus="getProdListByProdNameCn(scope.row.pssProdName)"
              placeholder="请选择">
              <el-option
                v-for="item in prodOptions"
                :key="item.id"
                :title="item.prodNameCn"
                :label="item.prodNameCn"
                :value="item"/>
            </el-select>
          </div>
        </template>
        <template
          slot="default-pssRegistNo"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.pssRegistNo"
              :regis-no="scope.row.pssRegistNo"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.isNoExpire"
              :regis-data="scope.row.registrationInfo || null"
            />
          </div>
          <!-- <el-button
            :disabled="!scope.row.pssRegistNo||!scope.row.pssRegistId"
            v-html="regisNoButton(scope.row, ['pssRegistNo', 'pssRegistId'])"
            type="text"
            @click="showPdfRegistion(scope.row.pssRegistId)"
          /> -->
        </template>
        <!-- <template
          slot="default-hspRegistNo"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.hspRegistNo"
              :regis-no="scope.row.hspRegistNo"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.isNoExpire"
              :regis-data="scope.row.registrationInfo"
            />
          </div> -->
        <!-- <el-button
            :disabled="!scope.row.hspRegistNo||!scope.row.hspRegistId"
            v-html="regisNoButton(scope.row, ['hspRegistNo', 'hspRegistId'])"
            type="text"
            @click="showPdfRegistion(scope.row.hspRegistId)"
          /> -->
        <!-- </template> -->
      </el-editable>
      <el-pagination
        align="right"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
  </div>
</template>

<script>
import {
  partFailtedDetailsTableData,
  detailTabsArr,
  recordFormDetail,
  ORDER_STATUS_TEXT,
  detailsSearchFormFailed
} from './const'
import { getFormatterPrice } from '@const/filter'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import {
  wscSaleOrderOrderDetailReceiveFailed, // 销售补货管理--批发/寄售--获取销售订单接收失败详情信息
  wscSaleOrderExceptionOrderOperate, // 销售补货管理--批发/寄售--接收失败的销售单操作
  authItemCommonQuery // 经销商saas——新建批发订单——添加授权产品查询
} from '@const/beforeSettleApi'
import ElEditable from '@components/el-editable'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
import { mapState } from 'vuex'
import SearchForm from '@components/businesscomponents/search'
export default {
  components: { ElEditable, RecordInfo, CellRegistration, SearchForm },
  data () {
    return {
      orderStatus: null,
      btns: [
        { type: 'primary', val: '暂存', handle: this.toStory, disabled: false },
        { type: 'primary', val: '再次接收', handle: this.acceptAgain, disabled: false }
      ],
      // 表格Loading
      tableLoading: false,
      // 表头
      partFailtedDetailsTableData,
      // 表格数据
      pssContainHspList: [],
      pssCompareHspList: [],
      recordFormDetail,
      // 详情ID
      id: this.$route.query.id,
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总共的条数
      headerInfo: {},
      roleType: 2,
      // 产品编码和名称模糊搜索
      prodOptions: [],
      detailsSearchFormFailed,
      submitLoading: false,
      searchQuery: {}
    }
  },
  filters: {
    getFormatterPrice
  },
  mounted () {
    this.list()
  },
  computed: {
    ...mapState(['companyId']),
    acticeBtns () {
      let status = this.orderStatus
      let arr = []
      if (status === 7) {
        arr = this.btns
      }
      return arr
    }
  },
  methods: {
    regisNoButton,
    showPdfRegistion,
    // 查询
    searchForm (val) {
      this.searchQuery = val
      this.list()
    },
    // 重置
    resetForm (val) {
      this.curPage = 1
      this.searchQuery = val
      this.list()
    },
    getValue (e) {
      // console.log(e.target.value)
      e.target.value = e.target.value.trim()
    },
    getProdListByCompanyProdCode (companyProdCode) {
      companyProdCode = companyProdCode || ''
      if ((/(^\s|\s$)/).test(companyProdCode)) {
        return false
      }
      if (companyProdCode === '' || companyProdCode.length < 4) {
        this.prodOptions = []
      } else {
        this.getProdList({ companyProdCode })
      }
    },
    getProdListByProdNameCn (prodNameCn) {
      prodNameCn = prodNameCn || ''
      if ((/(^\s|\s$)/).test(prodNameCn)) {
        return false
      }
      if (!prodNameCn) {
        return false
      }
      this.getProdList({ prodNameCn })
    },
    // 获取产品信息
    async getProdList (val) {
      // 配送商ID
      const downEnterpriseId = this.companyId
      const body = {
        ...val,
        page: 1,
        downEnterpriseId,
        pageSize: 20,
        authItemStatus: 2
      }
      const data = await this.$axios.$post(authItemCommonQuery, body)
      if (data.code === '0') {
        this.prodOptions = hasIn(data, 'payload.content') ? data.payload.content || []
          : []
      }
    },
    findByKey (value, key, list = this.prodOptions) {
      let itemArr = list.filter(col => {
        return Object.is(col[key], value)
      })
      const item = itemArr[0] || {}
      return item
    },
    // 字段对照
    initProdParams (target, source) {
      const obj = {
        pssAuthProdId: source.id,
        pssProdCode: source.companyProdCode,
        pssProdName: source.prodNameCn,
        pssProdSpecs: source.spec,
        pssProdModel: source.model,
        pssProdMinUnit: source.unit,
        pssRegistId: source.registId,
        pssRegistNo: source.registNo,
        pssManufacturer: source.manufacturer,
        upEnterpriseName: source.upEnterpriseName,
        pssProdBigCategory: source.bigType
      }
      Object.assign(target, obj)
    },
    // 选择编码或者名称
    setProdInfoByProdNameCn (value, row) {
      this.initProdParams(row, value)
    },
    // 选择编码或者名称
    setProdInfoByCompanyProdCode (value, row) {
      const obj = this.findByKey(value, 'companyProdCode')
      this.initProdParams(row, obj)
    },
    // 初始化全局操作
    initGlobalBtns (arr = this.acticeBtns) {
      const btn = {
        type: 'btn',
        arr: cloneDeep(arr)
      }
      this.$store.commit('changeLayoutHandle', btn)
    },
    changeOrderStatus (operateType) {
      // const filterList = item => item.pssAuthProdId
      const contrastItemList = this.pssContainHspList.map(({ saleDetailId, hspProdCode, pssAuthProdId }) => {
        return {
          orderItemId: saleDetailId,
          hspProdCode,
          pssAuthProdId
        }
      })
      const requestData = {
        saleOrderId: this.id,
        orderType: 1, // 订单类别（1-批发 2-寄售）
        operateType, // 订单操作（1-暂存，2-再次接收）
        contrastItemList
      }
      return this.$axios.$post(wscSaleOrderExceptionOrderOperate, requestData)
    },
    // 暂存
    async toStory () {
      const obj = this.findByKey('暂存', 'val', this.btns)
      obj.disabled = true
      this.initGlobalBtns(this.btns)
      try {
        const responesData = await this.changeOrderStatus(1)
        responesData.code === '0' && this.list()
      } finally {
        const obj = this.findByKey('暂存', 'val', this.btns)
        obj.disabled = false
        this.initGlobalBtns(this.btns)
      }
    },
    // 再次接收
    async acceptAgain () {
      const filterArr = this.pssContainHspList.filter(item => !item.pssAuthProdId)
      if (filterArr.length > 0) {
        return void this.$message.warning('产品对照未完成，不可接收')
      }
      const obj = this.findByKey('再次接收', 'val', this.btns)
      obj.disabled = true
      this.initGlobalBtns(this.btns)
      try {
        const responesData = await this.changeOrderStatus(2)
        responesData.code === '0' && this.$router.go(-1)
      } finally {
        const obj = this.findByKey('再次接收', 'val', this.btns)
        obj.disabled = false
        this.initGlobalBtns(this.btns)
      }
    },
    // 获取订单列表详情
    list () {
      // Loading加载开始
      this.tableLoading = true
      // 请求列表数据
      this.$axios
        .$post(wscSaleOrderOrderDetailReceiveFailed, {
          ...this.searchQuery,
          saleOrderId: this.id,
          page: this.curPage,
          pageSize: this.pageSize,
          orderType: 1 // 订单类别（1-批发 2-寄售）
        })
        .then(res => {
          let obj = hasIn(res, 'payload') ? res.payload : {}
          for (let key in obj) {
            if (key !== 'saleProductList') {
              if (!obj[key]) {
                obj[key] = `--`
              }
              if (key === 'orderStatus') {
                this.orderStatus = obj[key]
                obj[key] = ORDER_STATUS_TEXT[obj[key]]
              }
              this.$set(this.headerInfo, [key], obj[key])
            } else if (key === 'saleProductList') {
              this.pssContainHspList = obj[key].content
              // 获取配送商和医院对比的list集合
              this.pssCompareHspList = this.getPssCompareHspList(this.pssContainHspList)
              this.totalElements = obj[key].totalElements
            }
          }
          this.initGlobalBtns()
        })
        .finally(res => {
          this.tableLoading = false
        })
    },
    /**
     * @des 获取产品信息对比list
     */
    getPssCompareHspList (list) {
      let result = []
      list = list || []
      list.forEach(e => {
        let hspData = {
          saleDetailCode: '医院产品信息',
          pssProdCode: e.hspProdCode,
          pssProdName: e.hspProdName,
          pssProdSpecs: e.hspProdSpecs,
          pssProdModel: e.hspProdModel,
          pssProdMinUnit: e.hspProdMinUnit,
          pssManufacturer: e.hspManufacturer,
          pssRegistNo: e.hspRegistNo,
          price: e.price,
          purchaseCount: e.purchaseCount,
          detailAmount: e.detailAmount,
          remarks: e.remarks,
          hspProdBigCategory: e.hspProdBigCategory
        }
        result.push(e)
        result.push(hspData)
      })
      return result
    },
    // 合并单元格
    pssSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2) {
        if (column.property === 'saleDetailCode') {
          return [1, 2]
        }
        if (column.property === 'relationDetailCode') {
          return [0, 0]
        }
        if (columnIndex === 0) {
          return [0, 0]
        }
      } else {
        if (columnIndex === 0) {
          return [2, 1]
        }
      }
    },
    // 奇数行灰色
    getRowStyle ({ row, rowIndex }) {
      if (rowIndex % 2) {
        return 'color: #A7B1C7;'
      }
    },
    // 页码更改
    handleSizeChange (size) {
      this.curPage = 1
      this.pageSize = size
      this.list()
    },
    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.list()
    }
  }
}
</script>

<style lang="less">
.partDetailsBox {
  height: 100%;
  .partDetails {
    height: 100%;
    .order-info {
      // display: flex;
      .pagination {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
        padding-right: 0;
      }
    }
    .order-list-info {
      padding-left: 16px;
      height: 30px;
      line-height: 30px;
      span {
        margin-right: 30px;
        font-size: 14px;
        span {
          padding: 0 8px;
          color: black;
          font-size: 14px;
        }
        .add-color {
          color: blue;
        }
        .add-price {
          color: red;
        }
      }
    }
  }
  .dialog-info {
    .center-table {
      margin-top: 46px;
    }
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
